package com.github.cyf.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.cyf.common.constant.PermissionConstant;
import com.github.cyf.common.util.TreeUtil;
import com.github.cyf.domain.po.Permission;
import com.github.cyf.domain.po.Role;
import com.github.cyf.domain.vo.MenuVo;
import com.github.cyf.mapper.PermissionMapper;
import com.github.cyf.security.SecurityUtil;
import com.github.cyf.service.PermissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.cyf.service.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 权限信息表 服务实现类
 * </p>
 *
 * @author chenyifan
 * @since 2024-10-16
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private RoleService roleService;

    @Override
    public List<MenuVo> selectTree() {
        List<Permission> permissions = null;
        long loginId = StpUtil.getLoginIdAsLong();
        if (SecurityUtil.isSuperAdmin(loginId)) {
            permissions = this.list(new LambdaQueryWrapper<Permission>().eq(Permission::getEnable, 1));
        } else {
            permissions = queryPermissionByUserId(loginId);
        }
        List<MenuVo> menuVos = new ArrayList<>();
        for (Permission permission : permissions) {
            MenuVo menuVo = new MenuVo();
            BeanUtils.copyProperties(permission, menuVo);
            menuVos.add(menuVo);
        }
        return TreeUtil.buildTree(menuVos, MenuVo::getPid, MenuVo::getId, ele -> PermissionConstant.ROOT_MENU_ID == ele.getPid(), MenuVo::setChildren);
    }

    @Override
    public List<Permission> queryPermissionByUserId(Long userId) {
        List<Role> roles = roleService.queryRoleByUserId(userId);
        if (CollectionUtils.isEmpty(roles)) {
            return new ArrayList<>();
        }
        List<Long> roleIds = roles.stream().map(Role::getId).collect(Collectors.toList());
        return this.baseMapper.queryPermissionByRoleIds(roleIds);
    }

    @Override
    public List<Permission> queryPermissionByRoleId(Long roleId) {
        return this.baseMapper.queryPermissionByRoleIds(Collections.singletonList(roleId));
    }

    @Override
    public List<Permission> queryPermissionByRoleIds(List<Long> roleIds) {
        return this.baseMapper.queryPermissionByRoleIds(roleIds);
    }
}